package com.example.redis;


import com.example.redis.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.lang.Nullable;

import javax.annotation.PostConstruct;

@Configuration
public class RedisTemplateConfiguration {

    @Bean
    public RedisTemplate<Long, User> userRedisTemplate(RedisConnectionFactory connectionFactory){
        RedisTemplate<Long, User> userRedisTemplate = new RedisTemplate<>();
        // 设置 connectionFactory
        userRedisTemplate.setConnectionFactory(connectionFactory);
        // 设置 keySerializer
        userRedisTemplate.setKeySerializer(new UserKeySerializer());
        // 设置 valueSerializer
        userRedisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<User>(User.class));

        return userRedisTemplate;
    }

    /**
     * User Cache Key Serializer
     */
    static class UserKeySerializer implements RedisSerializer<Long>{
        private final String keyPre;
        UserKeySerializer(){
            this.keyPre = "user:";
        }
        @Override
        public byte[] serialize(Long aLong) throws SerializationException {
            String key = this.keyPre + aLong;
            return key.getBytes();
        }

        @Override
        public Long deserialize(byte[] bytes) throws SerializationException {
            String key = new String(bytes);
            return Long.valueOf(key.replace(keyPre, ""));
        }
    }
}
